<template>
    <el-select v-model="sval" :class="className" :popper-class="popperClass" :disabled="disabled" clearable :placeholder="placeholder" :style="{width}" @change="onChcange">
        <el-option v-for="dt in lists" :key="dt.agentId" :value="dt.agentId" :label="dt.agentName" />
    </el-select>
</template>
<script setup>
import {ref,onMounted,watch,nextTick} from "vue"
import {getAgentList} from '@/api/user'
import { useUserStore } from '@/pinia/modules/user'

const userStore = useUserStore()

const props = defineProps({
    modelValue:'',
    width:{
        type:String,
        default:'100%'
    },
    params:{  // 查询条件
        type:Object,
        default:{}
    }, 
    disabled:{
        type:Boolean,
        default:false 
    },
    className:'',
    popperClass:"",
    optLists:'',
    placeholder:'',
    defaultIndex:'' //默认显示第几个
})
const emit = defineEmits(['update:modelValue','change'])
const sval = ref('')
const lists = ref('')

onMounted(()=>{ 
    //getTableData()
    if(props.optLists){
        lists.value = props.optLists
        sval.value = props.modelValue || '' // 设置默认选项
    }else{
        getTableData()
    } 
})

watch(()=>props.modelValue,(n,o)=>{
    sval.value = n
})
watch(()=>props.optLists,(n,o)=>{
    lists.value = n
})

const getTableData = async (params) => {
    let pm = params?params:props.params
    const res = await getAgentList({ pageIndex: 1, pageSize: 10000,...pm})
    if (res.code == 200) {
        lists.value = res.data.data
        //sval.value = props.modelValue || ''  //设置默认选项
        if(props.modelValue){
            sval.value = props.modelValue 
        }else if(props.defaultIndex || props.defaultIndex==0){
            sval.value = lists.value[props.defaultIndex].agentId
            onChcange()
        }
    }
}

const onChcange = ()=>{
    emit('update:modelValue',sval.value) 
    if(sval.value){
        emit('change',lists.value.find(ele =>ele.agentId == sval.value))
    }else{
        emit('change',{}) 
    }
}

defineExpose({getTableData})

</script>

<style scoped lang="scss">
</style>